package com.appbee.adminshell.client;

import javax.inject.Inject;
import javax.inject.Provider;

import com.appbee.adminshell.shared.AdminRequestFactory;
import com.appbee.core.client.place.NamedPlace;
import com.appbee.core.client.place.PlaceControl;
import com.appbee.user.client.gin.WebUserProxyProvider;
import com.appbee.user.shared.proxy.WebUserProxy;
import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.web.bindery.requestfactory.shared.Receiver;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.ui.HasWidgets;

public class AdminApplication
{
	private final ActivityMapper activityMapper;
	private final Provider<Shell> shellProvider;
	private final PlaceHistoryHandler historyHandler;
	private final PlaceControl placeController;
	private final AdminRequestFactory rf;
	private final EventBus eventBus;

	@Inject
	public AdminApplication(ActivityMapper activityMapper,
			Provider<Shell> shellProvider, PlaceHistoryHandler historyHandler,
			PlaceControl placeController, AdminRequestFactory rf,
			EventBus eventBus)
	{
		super();
		this.activityMapper = activityMapper;
		this.shellProvider = shellProvider;
		this.historyHandler = historyHandler;
		this.placeController = placeController;
		this.rf = rf;
		this.eventBus = eventBus;
	}

	public void start(final HasWidgets container)
	{
		Request<WebUserProxy> request = rf.getMemberService()
				.getCurrentUser(
				Location.getHref());
		request.with("member");
		request.fire(new Receiver<WebUserProxy>()
		{

			@Override
			public void onSuccess(WebUserProxy user)
			{
				WebUserProxyProvider.setUser(user);
				startApp(container, user);
			}

		});
	}

	private void startApp(HasWidgets container, WebUserProxy user)
	{
		Shell shell = shellProvider.get();
		String nickName = user.getNickName();
		shell.setUserLabel(nickName);
		container.add(shell);

		// Start activitymanager
		ActivityManager aMan = new ActivityManager(activityMapper, eventBus);
		aMan.setDisplay(shell.getMainPanel());

		// Register placeControler with default place.
		NamedPlace defaultPlace = new NamedPlace("picasa");
		historyHandler.register(placeController, eventBus, defaultPlace);

		// Goes to the place represented on URL else default place
		historyHandler.handleCurrentHistory();
	}
}
